<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>销售出库编辑</title>
<link href="/resources/lib/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
<link href="/resources/lib/ligerUI/skins/ligerui-icons.css" rel="stylesheet" type="text/css" />
<script src="/resources/lib/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/resources/lib/ligerUI/js/ligerui.all.js" type="text/javascript"></script>
<script src="/resources/lib/jquery-validation/jquery.validate.min.js" type="text/javascript"></script> 
<script src="/resources/lib/jquery-validation/jquery.metadata.js" type="text/javascript"></script>
<script src="/resources/lib/jquery-validation/messages_cn.js" type="text/javascript"></script>
<script src="/resources/lib/json2.js" type="text/javascript"></script>
<script src="/resources/js/jsF7.js" type="text/javascript"></script>
<script src="/resources/js/selectData.js" type="text/javascript"></script>
<script src="/resources/js/themis.js" type="text/javascript"></script>
<script src="/resources/js/validation.js" type="text/javascript"></script>

<script type="text/javascript">
	var form1;
	var form2;
	var grid;
	$(function(){
	    //工具条
	    $("#toptoolbar").ligerToolBar({ items: [
	        	{ text: '保存', id:'save',click: saveForm,icon: 'save' },
	        	{ text: '提交', id:'save',click: submitForm },
	        	{ text: '审核', id:'save',click: auditForm },
	        	{ text: '反审核', id:'save',click: unAuditForm},

	    	]
	    });
        //创建表单(头部)
        form1 = $("#form1").ligerForm({
        inputWidth: 170, labelWidth: 90, space: 40,
        validate:true,
        fields: [
                 { display: "单据编号", name: "number", type: "text",newline: false, validate: { required: true, minlength: 5 } },
 	             { display: "部门", name: "depGroup.uuid", newline: false, type: "popup",textField:'depGroup.name',
	            	 editor: {
	                    grid: getDepGroupGrid(true),
	                    valueField:'uuid',
	                    textField: 'name',
	                    parms :{date:new Date().getTime()},
	                    width: 300,
	                    height:100,
	                    realTimeLoad:true
	           	 	}
	             },
                 { display: "出库日期", name: "bizDate", type: "date",newline: false, validate: { required: true, minlength: 5 } },
 	             { display: "客户", name: "customer.uuid", newline: false, type: "popup",textField:'customer.name',
	            	 editor: {
	                    grid: getCustomerGrid(true),
	                    valueField:'uuid',
	                    textField: 'name',
	                    parms :{date:new Date().getTime()},
	                    width: 300,
	                    height:100,
	                    realTimeLoad:true
	           	 	}
	             },
		        { display: "业务类型", name: "bizType", newline: false,  type: "select", readonly:true,editor: {data:getPurBizTypeSelect()}},
				{ display: "备注", name: "remark", newline: true, type: "text", width: 470}
            ]
        });
        
        //创建分录
        grid = $("#grid").ligerGrid({
            columns: [
            	        { display: '销售订单编号', name: 'saleOrderEntry.uuid', type: 'popup', width: 100,textField:'saleOrderEntry.saleOrder.number',
            	          	editor: {type: 'popup',
                             grid: getSaleOrderGrid(true),
                             valueField: 'uuid',
                             textField: 'saleOrder.number',
                             parms :{deliveryWay:"ziti"},
                             width: 300,
                             height:100,
                             realTimeLoad:true,
                             onSelected:function(e){
                            	  console.log(grid);
                            	 var ec =  grid.curEditColumn;
     					    	 for(var i=0;i<e.data.length;i++){
      					    		var row = null;
    					    		 if(i==0){
    					    			row = ec.rowData;
    					    			this.setValue(e.data[i].uuid);
    					    			this.setText(e.data[i].saleOrder.number);
    					    		 }else{
    					    			row = grid.addRow();
    					    			grid.updateCell('saleOrderEntry.uuid', e.data[i], row);
    					    		 }
     	                        	 grid.updateCell('material.uuid', e.data[i].material, row);
     	                        	 grid.updateCell('materialName', e.data[i].materialName, row);
     	                         	 grid.updateCell('materialStandard', e.data[i].materialStandard, row);
     	 					    	 grid.updateCell('jilUnit.uuid', e.data[i].jilUnit, row);
     					    	 }
                             }
                    	  }
            	        }, 
              	        { display: '发运单编号', name: 'dispatchEntry.uuid', type: 'popup', width: 100,textField:'dispatchEntry.dispatch.number',
            	          	editor: {type: 'popup',
                             grid: getDispatchGrid(true),
                             valueField: 'uuid',
                             textField: 'dispatch.number',
                             parms :{flag:'saleOutStorage'},
                             width: 300,
                             height:100,
                             realTimeLoad:true,
                             onSelected:function(e){
                            	 console.log(grid);
                            	 var ec =  grid.curEditColumn;
     					    	 for(var i=0;i<e.data.length;i++){
      					    		var row = null;
	   					    		 if(i==0){
	   					    			row = ec.rowData;
	   					    			this.setValue(e.data[i].uuid);
	   					    			this.setText(e.data[i].dispatch.number);
	   					    		 }else{
	   					    			row = grid.addRow();
	   					    			grid.updateCell('dispatchEntry.uuid', e.data[i], row);
	   					    		 }
     					    		 grid.updateCell('dispatch.uuid', e.data[i].saleOrder, row);
     	                        	 grid.updateCell('material.uuid', e.data[i].material, row);
     	                        	 grid.updateCell('materialName', e.data[i].materialName, row);
     	                         	 grid.updateCell('materialStandard', e.data[i].materialStandard, row);
     	 					    	 grid.updateCell('jilUnit.uuid', e.data[i].jilUnit, row);
     					    	 }
                             }
                    	  }
            	        },                       
                      
          	        { display: '商品编码', name: 'material.uuid', type: 'popup', width: 100,textField:'material.number',
        	          	editor: {type: 'popup',
                         grid: getMaterialGrid(true),
                         valueField: 'uuid',
                         textField: 'number',
                         parms :{date:new Date().getTime()},
                         width: 300,
                         height:100,
                         realTimeLoad:true,
                         onSelected:function(e){
                        	var ec =  grid.curEditColumn;
                        	grid.updateCell('materialName', e.data[0].name, ec.rowData);
                        	grid.updateCell('materialStandard', e.data[0].standard, ec.rowData);
					    	grid.updateCell('jilUnit.uuid', e.data[0].baseUnit, ec.rowData);
                       	 // console.log(e);
                         }
                	  }
        	        },
          	        { display: '商品名称', name: 'materialName', width: 100, editor: { type: 'text' }},
          	        { display: '商品规格型号', name: 'materialStandard', width: 100, editor: { type: 'text' }},
          	      	{ display: "计量单位", name: "jilUnit.uuid", width: 100,newline: false, type: "popup",textField:"jilUnit.name",
 	             	   editor: {
 	             		  		type: 'popup',
 		                       grid: getBaseUnitMeasureGrid(true),
 		                       valueField:'uuid',
 		                       textField: 'name',
 		                       parms :{date:new Date().getTime()},
 		                       width: 300,
 		                       height:100,
 		                       realTimeLoad:true
 		              	 }   
 	                },
 	               { display: '出库数量', name: 'outStorageQty', width: 100, type: 'float', editor: { type: 'float',
	       	        	onChangeValue:function(value){
	       	        		var ec =  grid.curEditColumn;
	       	        		if(!isNaN(value)&&ec.rowData.conversionRate){
	            	        		grid.updateCell('foutStorageQty', formatCurrency(value/ec.rowData.conversionRate), ec.rowData);
	            	        		grid.updateTotalSummary();
	       	        		}
	       	        	}	
	       	        },render:function(item){
	       	        	return formatCurrency(item.outStorageQty);
	       	        },totalSummary:{type: 'sum'}},
					//{ display: "辅助计量单位", name: "fjilUnit.uuid", width: 100,newline: false, type: "popup",textField:"fjilUnit.baseUnitMeasure.name",
	              	//  editor: {				  
	              	//	  		type: 'popup',
	 	            //          grid: getfUnitMeasureGrid(true),
	 	            //          valueField:'uuid',
	 	            //          textField: 'baseUnitMeasure.name',
	 	            //            //
	 	            //           width: 300,
	 	            //           height:100,
	 	            //           realTimeLoad:true,
	 	            //         onButtonClick:function(){
	 	            //        	 var uuid= null;
	 	            //        	  try{
	 	            //        		 uuid =  grid.curEditColumn.rowData.material.uuid;
	 	            //        	  }catch(e){
	 	            //        		 uuid = null;
	 	            //        	  }
	 	            //        	if(uuid){
	 	            //        		this.options.parms = {materialId:uuid};
	 	            //        	}
		            //           },
		            //           onSelected:function(e){
		            //           	var ec =  grid.curEditColumn;
		            //           	if(e.data[0]){
		            //           		grid.updateCell('conversionRate', e.data[0].conversionRate, ec.rowData);
		            //          		grid.updateCell('forderQty', ec.rowData.orderQty/e.data[0].conversionRate, ec.rowData);
		            //           		grid.updateTotalSummary();
		            //           	}
		   			//	    	//grid.updateCell('jilUnit.uuid', e.data[0].baseUnit, ec.rowData);
		            //            }
	 	            //  	 }   
	 	            // },
	 	            //{ display: '辅助换算率', name: 'conversionRate', width: 100, type: 'float'},
	     	        //{ display: '辅助数量', name: 'forderQty', width: 100, type: 'float', editor: { type: 'float' ,
	     	        //	onChangeValue:function(value){
	     	        // 		var ec =  grid.curEditColumn;
	     	        //		if(!isNaN(value)&&ec.rowData.conversionRate){
	         	    //    		grid.updateCell('orderQty', formatCurrency(value*ec.rowData.conversionRate), ec.rowData);
	         	    //    		grid.updateTotalSummary();
	     	        //		}
	    	        //	}		
	     	        //},render:function(item){
	    	        //	return formatCurrency(item.forderQty);
	    	        //},totalSummary:{type: 'sum'}},
 	               	{ display: '批次', name: 'lot', width: 100, editor: { type: 'text' }},
          	        { display: '条码', name: 'barCode', width: 100, editor: { type: 'text' }},
          	        { display: '保质到期日', name: 'expiraDate', width: 100, editor: { type: 'date' }},
          	        { display: "仓库", name: "warehouse.uuid", width: 100,type: "popup",textField:'warehouse.name',
		            	 editor: {type: 'popup',
		                    grid: getWarehouseGrid(true),
		                    valueField:'uuid',
		                    textField: 'name',
		                    parms :{date:new Date().getTime()},
		                    width: 300,
		                    height:100,
		                    realTimeLoad:true
		           	   }
		            },          	        
		            { display: '出库单价', name: 'inStoragePrice', width: 100, editor: { type: 'float' }},
          	        { display: '出库金额', name: 'inStorageAmount', width: 100, editor: { type: 'float' }},
          	        { display: '税额', name: 'taxLimit', width: 100, editor: { type: 'float' }},
          	        { display: '价税合计', name: 'taxAmount', width: 100, editor: { type: 'float' }},
          	        { display: '核销数量', name: 'cancelQty', width: 100, editor: { type: 'number' }},
          	        { display: '备注', name: 'remark', width: 100, editor: { type: 'text' },totalSummary:{type: 'sum'}},
        	        { display: 'uuid',name: 'uuid',hide:true, width: 100, type: 'text' }

            ], usePager: false,width: '95%',height: '275px',enabledEdit: true,alternatingRow:true,
            checkbox: true,headerRowHeight:22, rowHeight:22, rownumbers:true,
            onAfterEdit: f_onAfterEdit,

            toolbar: { items: [
                               { text: '添加行', click: addNewRow,icon: 'add' },
                               { line: true },
                               { text: '删除行', click: delRow,icon: 'delete' }
                               ]
                     }
            
        });
        //创建表单(尾部)
        form2 = $("#form2").ligerForm({
        inputWidth: 170, labelWidth: 90, space: 40,
        validate:true,
        fields: [
            
            { display: "创建人", name: "createUser.uuid", type: 'popup',newline: false,textField: 'createUser.trueName',
            	 editor: {
                     grid: getSysUserGrid(true),
                     valueField:'uuid',
                     textField: 'trueName',
                     parms :{date:new Date().getTime()},
                     width: 300,
                     height:100,
                     realTimeLoad:true
            	 }
            },
            { display: "修改人", name: "alterUser.uuid", type: 'popup',newline: false,textField:'alterUser.trueName',
           	 editor: {
                    grid: getSysUserGrid(true),
                    valueField:'uuid',
                    textField: 'trueName',
                    parms :{date:new Date().getTime()},
                    width: 300,
                    height:100,
                    realTimeLoad:true
           	 }
           },
            { display: "审核人", name: "auditUser.uuid", type: 'popup',newline: false,textField:'auditUser.trueName',
              	 editor: {
                       grid: getSysUserGrid(true),
                       valueField:'uuid',
                       textField: 'trueName',
                       parms :{date:new Date().getTime()},
                       width: 300,
                       height:100,
                       realTimeLoad:true
              	 }
              },
            
            { display: "创建日期", name: "createDate", newline: false, type: "date"},
            { display: "修改日期", name: "alterDate", newline: false,  type: "date" },
            { display: "审核日期", name: "auditDate",newline: false, type: "date" },
            { display: "提交人", name: "submitUser.uuid", type: 'popup',newline: false,textField:'submitUser.trueName',
             	 editor: {
                      grid: getSysUserGrid(true),
                      valueField:'uuid',
                      textField: 'trueName',
                      parms :{date:new Date().getTime()},
                      width: 300,
                      height:100,
                      realTimeLoad:true/* ,
                      onSelected:function(e){
                    	  var edd = form2.getEditor("createUser.uuid"); //form中应用
                    	  edd.setText(e.text);
                    	  console.log(e);
                      } */
             	 }
             },
            { display: "提交日期", name: "submitDate",newline: false, type: "date" },
            { name: "uuid", type: "hidden" },
            { display: "单据状态", name: "status", newline: false, type: "select",editor: {data:getStatsSelect()} }
            ]
        });
      	var info = '${info}';
    	if( info != null && info != ""){
    		var infoData = JSON.parse(info);
    		console.log(infoData);
    		form2.setData(infoData);
    		form1.setData(infoData);
    		grid.set({ data: {Rows:infoData.entrys}}); 
    	}
    	//单据状态
   		setEditStatus('${editStatus}',form1,form2,grid);
        //设置不可编辑字段
   		form2.setAllEnabled(false);
	});
	
	 //编辑后事件 
	function f_onAfterEdit(e){
		/* if(e.column.name == "material.uuid"){
			alert(e.value);
			grid.updateCell('materialName', '3333', e.record);
		} */
	}
	function formatCurrency(num)
    {
        if (!num) return "0.00";
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0.00";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
       /*  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3)); */
        return (((sign) ? '' : '-') + '' + num + '.' + cents);
    }
	
</script>
</head>
<body>
  <div style="display: none;"></div>
  <div id="toptoolbar"></div>
  <form id="form1"></form>
  <div id="grid" style="margin-top:15x"></div>
  <form id="form2" style="margin-top:15px"></form>
</body>
<script type="text/javascript">
//添加分录
function addNewRow(){
	grid.addRow();
}
//删除分录
function delRow(){
	grid.deleteSelectedRow();
}
//保存
function saveForm(){
    if(form1.valid()){

		var delData = grid.getDeleted();
		var gridData = grid.getData();
		var form1Data = form1.getData();
		var form2Data = form2.getData();
		if(validationSave($.ligerDialog,form2Data.status)){
			return;
		};
		var formData = $.extend({}, form1Data,form2Data);
		formData.entrys = gridData;
		$.ajax({
	        loading: '正在保存数据中...',
	        type:'post',
	        url: "/saleOutStorage/saveOrUpdateSaleOutStorage",
			dataType:'json',
	        data: {formData:JSON.stringify(formData),delData:JSON.stringify(delData),gridData:JSON.stringify(gridData)},
	        success: function (data) {
					$.ligerDialog.success(data.message,'信息',function(){
						form2.setData(data.data);
				    });
	        },
	        error: function (message) {
	       	 	$.ligerDialog.error("保存失败");
	        }
	    });
    }
}
//提交
function submitForm(){
	var info = form2.getData();
	if(validationSubmit($.ligerDialog,info.status)){
		return;
	};
	$.ajax({
        loading: '正在保存数据中...',
        type:'post',
        url: "/saleOutStorage/submitSaleOutStorage",
		dataType:'json',
        data: {uuid:info.uuid},
        success: function (data) {
				$.ligerDialog.success(data.message,'信息',function(){
		    		form2.setData(data.data);
			    });
        },
        error: function (message) {
       	 	$.ligerDialog.error("提交失败");
        }
    });
}
//审核
function auditForm(){
	var info = form2.getData();
	if(validationAudit($.ligerDialog,info.status)){
		return;
	};
	$.ajax({
        loading: '正在审核数据中...',
        type:'post',
        url: "/saleOutStorage/auditSaleOutStorage",
		dataType:'json',
        data: {uuid:info.uuid},
        success: function (data) {
				$.ligerDialog.success(data.message,'信息',function(){
		    		form2.setData(data.data);
			    });
        },
        error: function (message) {
       	 	$.ligerDialog.error("审核失败");
        }
    });
}
//反审核
function unAuditForm(){
	var info = form2.getData();
	if(validationUnAudit($.ligerDialog,info.status)){
		return;
	};
	$.ajax({
        loading: '正在反审核数据中...',
        type:'post',
        url: "/saleOutStorage/unAuditSaleOutStorage",
		dataType:'json',
        data: {uuid:info.uuid},
        success: function (data) {
				$.ligerDialog.success(data.message,'信息',function(){
		    		form2.setData(data.data);
			    });
        },
        error: function (message) {
       	 	$.ligerDialog.error("反审核失败");
        }
    });
}
//不可编辑字段
function setBillEnable(){
	//form2.setEnabled(["createUser","createDate","submitUser","submitDate","auditUser","auditDate","alterUser","alterDate","status"],false); 
}
</script>
</html>